/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.common.dataset.util;

import org.vacoor.nothing.common.dataset.Record;

/**
 * Excel 工具类
 *
 * @author vacoor
 */
@SuppressWarnings("unused")
public abstract class ExcelHelper {
    private static final byte[] BIFF8_FILE_HEADER = {(byte) 0xD0, (byte) 0xCF, 0x11, (byte) 0xE0};
    public static final byte[] ZIP_FILE_HEADER = {0x50, 0x4b, 0x03, 0x04};

    /**
     * 是否是 excel 2003 的biff8 文件头
     * eg:
     * <p/>
     * PushbackInputStream pis = new PushbackInputStream(new FileInputStream("jxl.out.xls"), 4);
     * byte[] header = new byte[4];
     * pis.read(header);
     * pis.unread(header);
     *
     * @param header 文件的前4个字节
     * @return
     */
    public static boolean isBiff8Header(byte[] header) {
        return header != null &&
                header.length >= BIFF8_FILE_HEADER.length &&
                BIFF8_FILE_HEADER[0] == header[0] &&
                BIFF8_FILE_HEADER[1] == header[1] &&
                BIFF8_FILE_HEADER[2] == header[2] &&
                BIFF8_FILE_HEADER[3] == header[3];
    }

    /**
     * 是否是 excel 2007 的 Open Xml(zip) 文件头
     *
     * @param header 文件的前4个字节
     * @return
     */
    public static boolean isZipHeader(byte[] header) {
        return header != null &&
                header.length >= ZIP_FILE_HEADER.length &&
                ZIP_FILE_HEADER[0] == header[0] &&
                ZIP_FILE_HEADER[1] == header[1] &&
                ZIP_FILE_HEADER[2] == header[2] &&
                ZIP_FILE_HEADER[3] == header[3];
    }

    /**
     * 根据列名称(A,B,..)返回列索引,从0开始
     */
    public static int columnNameToIndex(String name) {
        int column = -1;

        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (!Character.isLetter(c)) {
                throw new IllegalArgumentException("字符: '" + c + "' 不是一个有效的列索引字符");
            }

            column = (column + 1) * 26 + c - 'A';
        }
        return column;
    }

    /**
     * 返回列索引所对应的列名称
     */
    public static String columnIndexToName(int index) {
        StringBuffer fragment = new StringBuffer();
        do {
            int t = index % 26;
            index /= 26;
            fragment.insert(0, fragment.length() == 0 ? (char) (t + 'A') : (char) (t - 1 + 'A'));
        } while (index != 0);
        return fragment.toString();
    }

    /**
     * 打印 DataRecord
     *
     * @param record
     */
    public static void printRecord(Record record) {
        System.out.print(record.getRow() + ": ");
        for (int i = 0; i < record.getFieldCount(); i++) {
            Object value = record.getValue(i);
            System.out.print(", " + (null == value ? "" : value));
        }
        System.out.println();
    }

    private ExcelHelper() {
    }
}
